package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.MemberDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author LiangTianQi
 * @describe
 * @date 2020/11/18 18:28
 */
@Service(interfaceClass = MemberService.class)
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private JedisPool jedisPool;

    @Override
    @Transactional
    public void check(Map map) {
        //1在业务中进行判断是否存在会员，不存在则创建一个
        String telephone = (String) map.get("telephone");
        Member member = memberDao.getByTelephone(telephone);
        //判断是否为空
        if (member == null) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            add(member);
        }

        //2想jedis中添加数据，当作全局session
        String json=JSON.toJSON(member).toString();
        Jedis jedis = jedisPool.getResource();
        jedis.setex(telephone, 60 * 30, json);
        jedis.close();
    }

    @Override
    public void add(Member member) {
        if (member.getPassword() != null) {
            String password = MD5Utils.md5(member.getPassword());
            member.setPassword(password);
        }
        memberDao.add(member);
    }

    @Override
    public List<Integer> getCountByMonth(List<String> months) {
        List<Integer> memberCounts = new ArrayList<>();
        for (String month : months) {
            String date = month + ".31";
            Integer memberCount= memberDao.getCountByMonth(date);
            memberCounts.add(memberCount);
        }

        return memberCounts;
    }

    @Override
    public void delete(Integer id) {
        memberDao.delete(id);
    }

    @Override
    public void update(Member member) {
        memberDao.update(member);
    }

    @Override
    public Member get(Integer id) {
        return memberDao.get(id);
    }

    @Override
    public PageResult getByConditions(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<Member> memberList=memberDao.getByConditions(queryPageBean.getQueryString());
        PageInfo pageInfo = new PageInfo(memberList);
        PageResult pageResult = new PageResult(pageInfo.getTotal(),pageInfo.getList());
        return pageResult;
    }


}
